/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * CoFuD.java
 *
 * Created on May 28, 2013, 2:56:00 PM
 */

package cofud;

import java.awt.Font;
import java.beans.PropertyVetoException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import java.io.File;
import java.util.regex.Pattern;

/**
 *
 * @author Rendra
 */
public class CoFuD extends javax.swing.JFrame {
    
    /** Creates new form CoFuD */
    public CoFuD() {
        initComponents();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        myDesktopPane = new javax.swing.JDesktopPane();
        bottom_panel = new javax.swing.JPanel();
        footLabel = new javax.swing.JLabel();
        buttonHome = new javax.swing.JButton();
        buttonLoad = new javax.swing.JButton();
        buttonExecute = new javax.swing.JButton();
        buttonGraph = new javax.swing.JButton();
        buttonSave = new javax.swing.JButton();
        top_separator = new javax.swing.JSeparator();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Comment Function Detection");
        setName("mainFrame"); // NOI18N

        footLabel.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        footLabel.setText("CoFuD App - INSTITUT TEKNOLOGI ADHI TAMA SURABAYA");

        javax.swing.GroupLayout bottom_panelLayout = new javax.swing.GroupLayout(bottom_panel);
        bottom_panel.setLayout(bottom_panelLayout);
        bottom_panelLayout.setHorizontalGroup(
            bottom_panelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, bottom_panelLayout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(footLabel)
                .addGap(162, 162, 162))
        );
        bottom_panelLayout.setVerticalGroup(
            bottom_panelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(bottom_panelLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(footLabel)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        buttonHome.setText("Home");
        buttonHome.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonHomeActionPerformed(evt);
            }
        });

        buttonLoad.setText("Load");
        buttonLoad.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonLoadActionPerformed(evt);
            }
        });

        buttonExecute.setText("Execute");
        buttonExecute.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonExecuteActionPerformed(evt);
            }
        });

        buttonGraph.setText("Graph");
        buttonGraph.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonGraphActionPerformed(evt);
            }
        });

        buttonSave.setText("Save");
        buttonSave.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonSaveActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(bottom_panel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(buttonHome)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(buttonLoad)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(buttonExecute)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(buttonGraph)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(buttonSave)
                        .addGap(0, 303, Short.MAX_VALUE))
                    .addComponent(top_separator, javax.swing.GroupLayout.DEFAULT_SIZE, 630, Short.MAX_VALUE)
                    .addComponent(myDesktopPane, javax.swing.GroupLayout.DEFAULT_SIZE, 630, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(buttonHome)
                    .addComponent(buttonLoad)
                    .addComponent(buttonExecute)
                    .addComponent(buttonGraph)
                    .addComponent(buttonSave))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(top_separator, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(myDesktopPane, javax.swing.GroupLayout.DEFAULT_SIZE, 360, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(bottom_panel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void buttonHomeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonHomeActionPerformed
        // TODO add your handling code here:
        runHome();
        // Set bold the text
        Font newHomeFont = new Font(buttonHome.getFont().getName(),Font.BOLD,buttonHome.getFont().getSize());
        buttonHome.setFont(newHomeFont);

        // Remove bold effect on text button
        Font newLoadFont = new Font(buttonLoad.getFont().getName(),Font.PLAIN,buttonLoad.getFont().getSize());
        buttonLoad.setFont(newLoadFont);
        Font newExeFont = new Font(buttonExecute.getFont().getName(),Font.PLAIN,buttonExecute.getFont().getSize());
        buttonExecute.setFont(newExeFont);
        Font newSaveFont = new Font(buttonSave.getFont().getName(),Font.PLAIN,buttonSave.getFont().getSize());
        buttonSave.setFont(newSaveFont);
        Font newGraphFont = new Font(buttonGraph.getFont().getName(),Font.PLAIN,buttonGraph.getFont().getSize());
        buttonGraph.setFont(newGraphFont);
    }//GEN-LAST:event_buttonHomeActionPerformed

    private void buttonLoadActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonLoadActionPerformed
        // TODO add your handling code here:
        clearDesktopPane();
        LoadSrcFile lf = new LoadSrcFile();
        myDesktopPane.add(lf);
        lf.setVisible(true);
        lf.setBorder(null);
        try {
            lf.setMaximum(true);
            ((javax.swing.plaf.basic.BasicInternalFrameUI)lf.getUI()).setNorthPane(null);
        } catch (PropertyVetoException ex) {
            Logger.getLogger(CoFuD.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        // Set bold the text
        Font newLoadFont = new Font(buttonLoad.getFont().getName(),Font.BOLD,buttonLoad.getFont().getSize());
        buttonLoad.setFont(newLoadFont);

        // Remove bold effect on text button
        Font newHomeFont = new Font(buttonHome.getFont().getName(),Font.PLAIN,buttonHome.getFont().getSize());
        buttonHome.setFont(newHomeFont);
        Font newExeFont = new Font(buttonExecute.getFont().getName(),Font.PLAIN,buttonExecute.getFont().getSize());
        buttonExecute.setFont(newExeFont);
        Font newSaveFont = new Font(buttonSave.getFont().getName(),Font.PLAIN,buttonSave.getFont().getSize());
        buttonSave.setFont(newSaveFont);
        Font newGraphFont = new Font(buttonGraph.getFont().getName(),Font.PLAIN,buttonGraph.getFont().getSize());
        buttonGraph.setFont(newGraphFont);
    }//GEN-LAST:event_buttonLoadActionPerformed

    private void buttonExecuteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonExecuteActionPerformed
        // TODO add your handling code here:
        // Set bold the text
        Font newExeFont = new Font(buttonExecute.getFont().getName(),Font.BOLD,buttonExecute.getFont().getSize());
        buttonExecute.setFont(newExeFont);

        // Remove bold effect on text button
        Font newLoadFont = new Font(buttonLoad.getFont().getName(),Font.PLAIN,buttonLoad.getFont().getSize());
        buttonLoad.setFont(newLoadFont);
        Font newHomeFont = new Font(buttonHome.getFont().getName(),Font.PLAIN,buttonHome.getFont().getSize());
        buttonHome.setFont(newHomeFont);
        Font newSaveFont = new Font(buttonSave.getFont().getName(),Font.PLAIN,buttonSave.getFont().getSize());
        buttonSave.setFont(newSaveFont);
        Font newGraphFont = new Font(buttonGraph.getFont().getName(),Font.PLAIN,buttonGraph.getFont().getSize());
        buttonGraph.setFont(newGraphFont);
        
        if(!MyProgram.myBridge.isSourceEmpty()){
            clearDesktopPane();
            Detection dt = new Detection();
            myDesktopPane.add(dt);
            dt.setVisible(true);
            dt.setBorder(null);
            try {
                dt.setMaximum(true);
                ((javax.swing.plaf.basic.BasicInternalFrameUI)dt.getUI()).setNorthPane(null);
            } catch (PropertyVetoException ex) {
                Logger.getLogger(CoFuD.class.getName()).log(Level.SEVERE, null, ex);
            }
        }else{
            JOptionPane.showMessageDialog(null, "Maaf, source file belum ditentukan", "Terjadi Kesalahan", JOptionPane.ERROR_MESSAGE);
        }
    }//GEN-LAST:event_buttonExecuteActionPerformed

    private void buttonGraphActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonGraphActionPerformed
        // TODO add your handling code here:
        // Set bold the text
        Font newGraphFont = new Font(buttonGraph.getFont().getName(),Font.BOLD,buttonGraph.getFont().getSize());
        buttonGraph.setFont(newGraphFont);

        // Remove bold effect on text button
        Font newLoadFont = new Font(buttonLoad.getFont().getName(),Font.PLAIN,buttonLoad.getFont().getSize());
        buttonLoad.setFont(newLoadFont);
        Font newHomeFont = new Font(buttonHome.getFont().getName(),Font.PLAIN,buttonHome.getFont().getSize());
        buttonHome.setFont(newHomeFont);
        Font newSaveFont = new Font(buttonSave.getFont().getName(),Font.PLAIN,buttonSave.getFont().getSize());
        buttonSave.setFont(newSaveFont);
        Font newExeFont = new Font(buttonExecute.getFont().getName(),Font.PLAIN,buttonExecute.getFont().getSize());
        buttonExecute.setFont(newExeFont);
        
        if(!MyProgram.myBridge.isPartEmpty()){
            clearDesktopPane();
            Graph gr = new Graph();
            myDesktopPane.add(gr);
            gr.setVisible(true);
            gr.setBorder(null);
            try {
                gr.setMaximum(true);
                ((javax.swing.plaf.basic.BasicInternalFrameUI)gr.getUI()).setNorthPane(null);
            } catch (PropertyVetoException ex) {
                Logger.getLogger(CoFuD.class.getName()).log(Level.SEVERE, null, ex);
            }
        }else{
            JOptionPane.showMessageDialog(null, "Maaf, proses eksekusi belum dijalankan", "Terjadi Kesalahan", JOptionPane.ERROR_MESSAGE);
        }
    }//GEN-LAST:event_buttonGraphActionPerformed

    private void buttonSaveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonSaveActionPerformed
        // TODO add your handling code here:
        // Set bold the text
        Font newSaveFont = new Font(buttonSave.getFont().getName(),Font.BOLD,buttonSave.getFont().getSize());
        buttonSave.setFont(newSaveFont);

        // Remove bold effect on text button
        Font newLoadFont = new Font(buttonLoad.getFont().getName(),Font.PLAIN,buttonLoad.getFont().getSize());
        buttonLoad.setFont(newLoadFont);
        Font newHomeFont = new Font(buttonHome.getFont().getName(),Font.PLAIN,buttonHome.getFont().getSize());
        buttonHome.setFont(newHomeFont);
        Font newGraphFont = new Font(buttonGraph.getFont().getName(),Font.PLAIN,buttonGraph.getFont().getSize());
        buttonGraph.setFont(newGraphFont);
        Font newExeFont = new Font(buttonExecute.getFont().getName(),Font.PLAIN,buttonExecute.getFont().getSize());
        buttonExecute.setFont(newExeFont);
        
        if(!MyProgram.myBridge.isSourceEmpty()){
            try{
                String [] flNm = MyProgram.myBridge.getSourceFile().split(Pattern.quote("\\"));
                String [] nmFl = (flNm[flNm.length-1]).split(Pattern.quote("."));
                String currDir = new File(".").getAbsolutePath();
                File f = new File(currDir.substring(0, currDir.length()-1)+nmFl[0]+".xml");
                f.createNewFile();
                saveXMLFile(f);
                JOptionPane.showMessageDialog(null, "Data tersebut berhasil disimpan pada "+currDir.substring(0, currDir.length()-1)+nmFl[0]+".xml", "Informasi", JOptionPane.INFORMATION_MESSAGE);
            }catch(Exception e){
                Logger.getLogger(CoFuD.class.getName()).log(Level.SEVERE, null, e);
            }
        }else{
            JOptionPane.showMessageDialog(null, "Maaf, source file belum ditentukan", "Terjadi Kesalahan", JOptionPane.ERROR_MESSAGE);
        }
    }//GEN-LAST:event_buttonSaveActionPerformed

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new CoFuD().setVisible(true);
            }
        });
    }

    /**
     * Clear all the myDesktopPane from Internal Frame
     */
    private void clearDesktopPane(){
        myDesktopPane.removeAll();
        myDesktopPane.repaint();
    }
    
    public void runHome(){
        clearDesktopPane();
        HomePage hp = new HomePage();
        myDesktopPane.add(hp);
        hp.setVisible(true);
        hp.setBorder(null);
        try {
            hp.setMaximum(true);
            ((javax.swing.plaf.basic.BasicInternalFrameUI)hp.getUI()).setNorthPane(null);
        } catch (PropertyVetoException ex) {
            Logger.getLogger(CoFuD.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
    public void saveXMLFile(File f){
        try{
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            Document doc = db.newDocument();
 
            Element rootElement = doc.createElement("code");
 
            StringBuilder fn = MyProgram.myBridge.getFunctions();
            StringBuilder cm = MyProgram.myBridge.getComments();
            String [] lineCm = cm.toString().split("\n");
            String [] lineFn = fn.toString().split("\n");
            int [] codeParts = MyProgram.myBridge.getPartCode();
            
            Element action_cm = doc.createElement("comments");
            action_cm.setAttribute("name", "Comments Of Code");
            for(String s : lineCm){
                Element result = doc.createElement("comment");
                result.setAttribute("name", "success");
                result.setTextContent(s);
                action_cm.appendChild(result);
            }
 
            Element action_fn = doc.createElement("functions");
            action_fn.setAttribute("name", "Functions Of Code"); 
            for(String s : lineFn){
                Element result = doc.createElement("function");
                result.setAttribute("name", "success");
                result.setTextContent(s);
                action_fn.appendChild(result);
            }
            
            // Simpan angka total dari 4 poin yang ada
            // ke dalam node XML "parts"
            Element action_pr = doc.createElement("parts");
            action_pr.setAttribute("name", "Code Reports"); 
            for(int i=0;i<4;i++){
                Element result = doc.createElement("part");
                result.setAttribute("name", "success");
                result.setTextContent(Integer.toString(codeParts[i]));
                action_pr.appendChild(result);
            }
 
            rootElement.appendChild(action_cm);
            rootElement.appendChild(action_fn);
            rootElement.appendChild(action_pr);
 
            doc.appendChild(rootElement);
 
            TransformerFactory tf = TransformerFactory.newInstance();
            Transformer t = tf.newTransformer();
            t.setOutputProperty(OutputKeys.ENCODING,"UTF-8");
            DOMSource source = new DOMSource(doc);
            StreamResult result = new StreamResult(f);
            t.transform(source, result); 
        }catch(Exception e){
            Logger.getLogger(CoFuD.class.getName()).log(Level.SEVERE, null, e);
        }
    }
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JPanel bottom_panel;
    private javax.swing.JButton buttonExecute;
    private javax.swing.JButton buttonGraph;
    private javax.swing.JButton buttonHome;
    private javax.swing.JButton buttonLoad;
    private javax.swing.JButton buttonSave;
    private javax.swing.JLabel footLabel;
    private javax.swing.JDesktopPane myDesktopPane;
    private javax.swing.JSeparator top_separator;
    // End of variables declaration//GEN-END:variables

}
